package com.zzyl.framework.interceptor;

import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    //获取请求头的token
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = tokenService.getToken(request);
        if (!StringUtils.hasLength(token)) {
            log.info("请求头中没有token！");
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        //解析token
        try {
            Claims claims = tokenService.parseToken(token);
            log.info(String.valueOf(claims));
            Long userID = claims.get("userID", Long.class);
            UserThreadLocal.set(userID);
            //放行
            log.info("token验证通过");
            return true;
        } catch (Exception e) {
            log.error("解析token失败", e);
            //如果解析失败，响应 401
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
    }
}
